package com.hellogood.work.evaluate.server.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hellogood.work.evaluate.server.db.DBHelper;
import com.hellogood.work.evaluate.shared.exception.DatabaseException;
import com.hellogood.work.evaluate.shared.po.Service;

public class ServiceDAO extends DBHelper {

	@Override
	public List<?> initializeObject(ResultSet rs) throws SQLException {
		List<Service> list = new ArrayList<Service>();
		if (rs != null) {
			while (rs.next()) {
				Service service = new Service();
				String serverCode = rs.getString("ServerCode");
				String serverName = rs.getString("ServerName");
				service.setServiceCode(serverCode == null ? "" : serverCode.trim());
				service.setServiceName(serverName == null ? "" : serverName.trim());
				service.setScore(rs.getInt("Score"));
				list.add(service);
			}
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<Service> getList() {
		String sql = "SELECT * FROM ServerType ORDER BY ServerCode";
		List<?> list = super.query(sql);
		return (List<Service>) list;
	}

	public Service getItem(String serviceCode) {
		String sql = "SELECT * FROM ServerType WHERE ServerCode = '" + serviceCode + "'";
		List<?> list = super.query(sql);
		if (list != null && list.size() > 0) {
			return (Service) list.get(0);
		}
		return null;
	}

	public String modify(Service s, boolean isModiy) {
		String sql = "INSERT INTO ServerType(ServerCode,ServerName,Score) VALUES('" + s.getServiceCode() + "','" + s.getServiceName() + "',"
				+ s.getScore() + ")";
		if (isModiy) {
			sql = "UPDATE ServerType SET ServerName = '" + s.getServiceName() + "',Score = " + s.getScore() + " WHERE ServerCode = '"
					+ s.getServiceCode() + "'";
		}
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			return "执行新建、修改服务信息错误";
		}
		return "执行新建、修改服务信息错误";
	}
}
